package com.hbk.base.util;

import org.apache.commons.codec.binary.Base64;
import org.jasypt.encryption.ByteEncryptor;
import org.jasypt.encryption.pbe.PooledPBEByteEncryptor;

import java.io.UnsupportedEncodingException;

public class JasyptUtil {

    private static ByteEncryptor getEncryptor(){

        String algorithm = "PBEWithMD5AndDES";
        int poolSize = 1;

        byte[] key = {80, 64, 115, 36, 42, 119, 48, 114, 68, 33};

        PooledPBEByteEncryptor encryptor = new PooledPBEByteEncryptor();
        encryptor.setAlgorithm(algorithm);
        String keyStr = null;
        try {
            // P@s$*w0rD!
            keyStr = new String(key,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        char[] chars = keyStr.toCharArray();
        encryptor.setPasswordCharArray(chars);
        encryptor.setPoolSize(poolSize);
        return encryptor;
    }

    public static String encode(String text){
        byte[] bytes = new byte[0];
        try {
            bytes = text.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        byte[] encryptBytes = getEncryptor().encrypt(bytes);
        String result = Base64.encodeBase64URLSafeString(encryptBytes);
        return result;
    }

    public static String decode(String text){
        byte[] bytes = Base64.decodeBase64(text);
        byte[] decryptBytes = getEncryptor().decrypt(bytes);
        String result = null;
        try {
            result = new String(decryptBytes, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }
}
